<?php
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
session_name(SESSION);
session_start();
$_SESSION[TINYMCE_UPLOAD] = 'uploads/tinymce/';

$myPdo = DbUtils::createPdoInst();
$page_id = MiscUtils::getParam('i', NULL);
$folder = basename(dirname(__FILE__));
$tag = MiscUtils::getParam('tag', 'product');
$product_track_id = MiscUtils::getParam('id', NULL);
$instance_id = MiscUtils::getParam('inid', 0);

$item = NULL;
$cond_vals = new stdClass(); 
$cond_vals->c = 't.track_id = :v1';
$cond_vals->v = array(':v1' => $product_track_id);
$tmp = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_product', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;

$objects = array();
$images = array();
$member_prices = array();
if (count($tmp) > 0) {
  $item = $tmp[0];
  $cond_vals = new stdClass(); 
  $cond_vals->c = 't.product_track_id = :v1';
  $cond_vals->v = array(':v1' => $item->track_id);
  $attrs = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_attr', $cond_vals,  't.id', 'ASC', NULL, NULL, NULL)->d;
  foreach ($attrs as $obj) {
    $cond_vals = new stdClass(); 
    $cond_vals->c = 't.product_attr_id = :v1';
    $cond_vals->v = array(':v1' => $obj->id);
    $obj->_opts = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_attr_opt', $cond_vals,  't.id', 'ASC', NULL, NULL, NULL)->d;
  }
  unset($obj);
  
  $cond_vals = new stdClass(); 
  $cond_vals->c = 't.product_track_id = :v1';
  $cond_vals->v = array(':v1' => $item->track_id);
  $objects = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_object', $cond_vals,  't.attr_opt_code', 'ASC', NULL, NULL, NULL)->d;

  $cond_vals = new stdClass(); 
  $cond_vals->c = 't.product_track_id = :v1';
  $cond_vals->v = array(':v1' => $item->track_id);
  $images = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_img', $cond_vals,  't.id', 'ASC', NULL, NULL, NULL)->d;
  
  $cond_vals = new stdClass(); 
  $cond_vals->c = 't.product_track_id = :v1';
  $cond_vals->v = array(':v1' => $item->track_id);
  $member_prices = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_member_price', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
}
$members = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer_member', NULL, 't.total_spent', 'ASC', NULL, NULL, NULL)->d;
$brands = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_brand', NULL, 't.name', 'ASC', NULL, NULL, NULL)->d;
$categories = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_category', NULL, 't.order', 'ASC', NULL, NULL, NULL)->d;
//$data->members = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_member', NULL, 't.id', 'ASC', NULL, NULL, NULL)->d;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
* {
  font-family: Trebuchet MS;
  font-size: 12px;
  padding: 0;
  margin: 0;
}
table.form {
  background-color: #fff;
  border-top: 1px solid #222;
  border-left: 1px solid #222;
}
table.form th.header {
  text-align: left;
  color: #fff;
  background-color: #222;
  padding-left: 5px;
  font-weight: bold;
  height: 25px;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
}
table.form td {
  vertical-align: middle;
}
table.form td.title {
  background-color: #666;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
  width: 150px;
  color: #fff;
  padding: 3px 5px; 
  vertical-align: top;
  font-weight: bold;
}
table.form td.light {
  background-color: #ddd !important;
  color: #333 !important;
}
table.form td.content {
  padding-left: 2px;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
  width: 610px;
}
table.form td.content input[type=text],textarea,select,option {
  width: 98%;
  border: 0;
  padding: 0;
  margin: 0;
}
table.form td.content select {
  border: 1px solid #ddd;
}
table.form td.content input[type=text] {
  height: 20px;
}
table.form td.content textarea {
  height: 50px;
  resize: none;
}
table.form2 {
  background-color: #fff;
  border-top: 1px solid #aaa;
  border-left: 1px solid #aaa;
  width: 99%;
  margin-bottom: 5px;
}
table.form2 td.header {
  text-align: left;
  color: #666;
  background-color: #aaa;
  padding: 0;
  font-weight: bold;
  height: 25px;
  border-bottom: 1px solid #aaa;
  border-right: 1px solid #aaa;
}
table.form2 td.content {
  padding-left: 2px;
  border-bottom: 1px solid #aaa;
  border-right: 1px solid #aaa;
}
table.form3 {
  background-color: #fff;
  border: 1px solid #666;
  color: #000;
  padding: 2px;
  cursor: pointer;
  display: inline-block;
  margin: 2px 0 0 2px;
  font-weight: bold;
}
table.form3dark {
  background-color: #cecece;
  border: 1px solid #222;
  font-weight: normal;
}
table.form3 td.text {
  width: 35px;
  height: 20px;
  overflow: hidden;
  display: inline-block;
}
table.form3 td.img {
  width: 16px;
  padding-left: 2px;
}
table.form3:hover td {
  background: #fff;
}
table.form4 {
  background-color: #e9e9e9;
  border: 1px solid #666;
  color: #000;
  padding: 2px;
  padding-bottom: 20px;
  cursor: pointer;
  display: inline-block;
  margin: 2px;
  font-weight: bold;
}
table.list {
  border-left: 1px solid #666;
  border-top: 1px solid #666;
  font-size: 12px;
  width: 99%;
  margin-bottom: 5px;
}
table.list tr.sort td {
  text-align: left;
  height: 28px;
  background-color: #ddd;
  padding: 0 5px; 
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  font-weight: bold;
  vertical-align: middle;
  cursor: pointer;
  color: #333;
}
table.list tr.rowodd td {
  padding: 0 5px;
  height: 25px;
  background-color: #eee;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
  vertical-align: middle;
}
table.list tr.roweven td {
  padding: 0 5px;
  height: 25px;
  background-color: #fff;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
  vertical-align: middle;
}
table.list tr.rowodd:hover td {
  background-color: #f4f3b2;
}
table.list tr.roweven:hover td {
  background-color: #f4f3b2;
}
.imgbtn {
  background-image: url(assets/imgs/save.png);
  background-repeat: no-repeat;
  background-position: 5px 2px;
  padding: 5px 5px 5px 30px;
  border: 1px solid #666;
  background-color: #fff;
  cursor: pointer;
  border-radius: 3px;
}
.imgbtn:hover {
  background-color: #eee;
}
.add {
  background-image: url(assets/imgs/add16.png) !important;
  padding: 2px 2px 2px 20px !important;
  margin: 2px 0 !important;
}
.add2 {
  background-image: url(assets/imgs/add16_2.png) !important;
  padding: 2px 2px 2px 20px  !important;
}
.imgico {
  cursor: pointer;
}
ul.hztl li {
  display: inline;
  vertical-align: middle;
}
</style>
</head>
<body>
<table class="form" cellpadding=0 cellspacing=0>
  <tr><th class="header" colspan=2>Edit Product</th></tr>
  <tr>
    <td class="title">Product Name</td>
    <td class="content"><input id="name" class="text" value="<?php echo (isset($item->name) ? $item->name : ''); ?>" type="text" ></input></td>
  </tr>
  <tr>
    <td class="title">Brand</td>
    <td class="content"><select id="brand_select"></select></td>
  </tr>
  <tr>
    <td class="title">Category</td>
    <td class="content"><select id="category_select"></select></td>
  </tr>
  <tr>
    <td id="member_title" class="title">Market Price</td>
    <td id="member_content" class="content">
      <input class="text" id="price" style="width: 50%;" value="<?php echo ($item ? $item->price : '0.00'); ?>" type="text"></input>
      <input id="member_checkbox" type="checkbox" onclick="set_members();" <?php echo ($item && $item->enabled_member_price == 1 ? "checked='checked'" : ''); ?>></input> Member Price（Default=Market Price）
    </td>
  </tr>
  <tr id="memberdiv">
    <td class="title">&nbsp;</td>
    <td class="content" id="members">&nbsp;</td>
  </tr>
  <tr>
    <td class="title">Visible</td>
    <td class="content">
      <input id="available" type="checkbox" name="status" <?php echo (!$item || $item->status == 1 ?  "checked='checked'" : ''); ?>></input>
    </td>
  </tr>
  <tr>
    <td class="title">Stock Enabled</td>
    <td class="content">
      <ul class="hztl">
        <li><input id="stock_checkbox" type="checkbox" <?php echo ($item && $item->enabled_stock ? "checked='checked'" : ''); ?> onclick="set_attrs();"></input></li>
        <span id="stock_without_attrs">
          <li><b>Current Stock:</b></li>
          <li><input id="stock" style="width: 80px;<?php if ($item && $item->stock <= $item->stock_alert) echo 'color: red;'; ?>" type="text" value="<?php echo ($item ? $item->stock : 0); ?>"></input></li>
          <li><b>Alert if less than:</b></li>
          <li><input id="stock_alert" style="width: 80px;" type="text" value="<?php echo ($item ? $item->stock_alert : 0); ?>"></input></li>
        </span>
        <span id="stock_with_attrs">
          <li><b>Manage Stock in Item Table</b></li>
        </span>
      </ul>
    </td>
  </tr>
  <tr>
    <td class="title">Delivery Enabled</td>
    <td class="content"><input id="ship_checkbox" type="checkbox" <?php echo (!$item || $item->enabled_delivery == 1 ? "checked='checked'" : ''); ?>></input></td>
  </tr>
  <tr>
    <td class="title" id="attr_title">Attributes</td>
    <td class="content" id="attr_content"><button class="imgbtn add" onclick="save_attr(null);">New Attr</button>（e.g. Color, Size）</td>
  </tr>
  <tr id="attrdiv">
    <td class="title">&nbsp;</td>
    <td class="content" id="attrs">&nbsp;</td>
  </tr>
  <tr>
    <td class="title">Brief Description</td>
    <td class="content"><textarea id="intro"><?php echo ($item ? $item->intro : ''); ?></textarea></td>
  </tr>
  <tr>
    <td class="title">Detailed Description</td>
    <td class="content"><textarea id="detail" ><?php echo ($item ? $item->details : ''); ?></textarea></td>
  </tr>
  <tr>
    <td class="title">
      Images (<?php echo PROD_WIDTH . ' x ' . PROD_HEIGHT; ?>)
      <br>
      <div id="spanButtonPlaceHolder"></div>
      <div id="cancelBtnId" style="display: none;"></div>
    </td>
    <td class="content">
      <ul id="images" class="hztl"></ul>
    </td>
  </tr>
</table>
<button class="imgbtn" onclick="save();" style="margin-top: 5px;">Save</button>
<script type="text/javascript" src="../../../libs/json/json2.js"></script>
<script type="text/javascript" src="../../../libs/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="../../../libs/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="../../../incls/js/myutils.js"></script>
<script type="text/javascript" src="../../../incls/js/pageutils.js"></script>
<script type="text/javascript" src="../../../libs/swfupload/swfupload.js"></script>
<script type="text/javascript" src="../../../libs/swfupload/swfupload.queue.js"></script>
<script type="text/javascript" src="../../../libs/swfupload/myupload.js"></script>
<link rel="stylesheet" href="assets/css/prettyPhoto.css" type="text/css" media="screen" charset="utf-8" />
<script src="assets/js/jquery.prettyPhoto.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
  var _item = JSON.parse('<?php echo addslashes(json_encode($item)); ?>');
  var _brands = JSON.parse('<?php echo addslashes(json_encode($brands)); ?>');
  var _categories = JSON.parse('<?php echo addslashes(json_encode($categories)); ?>');
  var _attrs = JSON.parse('<?php echo isset($attrs) ? addslashes(json_encode($attrs)) : '[]'; ?>');
  var _objects = JSON.parse('<?php echo isset($objects) ? addslashes(json_encode($objects)) : '[]'; ?>');
  var _images = JSON.parse('<?php echo isset($images) ? addslashes(json_encode($images)) : '[]'; ?>');
  var _members = JSON.parse('<?php echo isset($members) ? addslashes(json_encode($members)) : '[]'; ?>');
  var _member_prices = JSON.parse('<?php echo isset($member_prices) ? addslashes(json_encode($member_prices)) : '[]'; ?>');
  
  $(function(){
    <?php if (!$product_track_id) { ?>
    parent.location.href = parent.document.URL + '<?php echo '&id=' . MiscUtils::unique(); ?>';
    return;
    <?php } ?>
    //NOT GOOD
    var div = parent.document.getElementById('<?php echo LAST_NAV; ?>');
    var div_parent = div.parentNode;
    var value = div_parent.firstChild.nodeValue;
    MyUtils.removeChildElements(div_parent);
    var elm;
    elm = parent.document.createElement('a');
    elm.href = '#';
    elm.style.color = '#000';
    elm.style.fontSize = '13px';
    elm.style.fontWeight = 'bold';
    elm.onclick = function() {
      var url = parent.document.URL.replace('&script=index_product', '');
      url = url.replace('&id=<?php echo $product_track_id; ?>', '');
      url = url.replace('#', '');
      parent.location.href = url;
    };
    elm.appendChild(parent.document.createTextNode(value));
    div_parent.appendChild(elm);

    var td;
    td = div_parent.parentNode.insertCell(-1);
    td.style.width = '20px';
    td.style.textAlign = 'center';
    td.style.color = '#aaa';
    td.appendChild(parent.document.createTextNode('>'));
    
    td = div_parent.parentNode.insertCell(-1);
    td.style.height = '25px';
    td.style.color = '#333';
    td.style.fontSize = '13px';
    if (_item && _item.id) {
      td.appendChild(parent.document.createTextNode(MyUtils.getShort(_item.name, 12)));
    } else {
      td.appendChild(parent.document.createTextNode('New Product'));
    }
    //NOT GOOD END
    
    new MyUpload('spanButtonPlaceHolder', '<?php echo basename(__FILE__, '.php'); ?>.upload.php', function(msgs) {
      for (var idx in msgs) {
        var obj = JSON.parse(msgs[idx]);
        _images.push(obj);
      }
      set_images();
    }, {
      dir: '../../../',
      button_image_url: 'assets/imgs/browse.png',
      button_width: 80,
      button_height: 25,
      file_types: '*.jpg;*.jpeg;*.png;*.gif',
      file_types_description: 'Image Files',
      cancelBtnId: 'cancelBtnId',
      post_params: {
        product_track_id: '<?php echo $product_track_id; ?>'
      },
      debug: 0
    });
    
    set_category(PageUtils.getRoot(JSON.parse('<?php echo addslashes(json_encode($categories)); ?>')), $('#category_select')[0], '');
    set_brand();

    tinyMCE.init( {
      // General options
      mode: 'exact',
      elements: 'detail',
      theme: 'advanced',

      plugins: 'pdw,filebrowser,autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist',
      // Theme options
      theme_advanced_buttons1: 'pdw_toggle,|,undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,|,forecolor,backcolor,|,image,media,|,preview',
      theme_advanced_buttons2: 'search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime',
      theme_advanced_buttons3: 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,advhr,|,print,|,ltr,rtl,|,fullscreen',
      theme_advanced_buttons4: 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak',
      theme_advanced_toolbar_location: 'top',
      theme_advanced_toolbar_align: 'left',
      theme_advanced_statusbar_location: 'bottom',
      theme_advanced_resizing: true,

      file_browser_callback: 'filebrowser',
      pdw_toggle_on: '1',
      pdw_toggle_toolbars: '2,3,4',

      height: 500,
      
      // Example content CSS (should be your site CSS)
      theme_advanced_font_sizes: '10px,11px,12px,13px,14px,15px,16px,17px,18px,19px,20px,21px,22px,23px,24px,25px,26px,27px,28px,29px,30px'
    });
    set_attrs();
    set_members();
    set_images();
  });

  function set_images() {
    MyUtils.removeChildElements($('#images')[0]);
    var li;
    for (var idx in _images) {
      var obj = _images[idx];
      li = document.createElement('li');
      li.appendChild(__get_img(obj));
      $('#images')[0].appendChild(li);
    }
    __set_pp();
    document.body.style.height = parseFloat(Math.max(document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight), 10) + parseFloat($('#images')[0].offsetHeight, 10) + 'px';
    parent.updateHeight_<?php echo $instance_id; ?>();
  }
  
  function set_stocks() {
    if (!$('#stock_checkbox')[0].checked) {
      $('#stock_with_attrs')[0].style.display = 'none';
      $('#stock_without_attrs')[0].style.display = 'none';
      return;
    }
    if (_attrs.length > 0) {
      $('#stock_without_attrs')[0].style.display = 'none';
      $('#stock_with_attrs')[0].style.display = 'inline-block';
    } else {
      $('#stock_with_attrs')[0].style.display = 'none';
      $('#stock_without_attrs')[0].style.display = 'inline-block';
    }
    parent.updateHeight_<?php echo $instance_id; ?>();
  };

  function set_attrs() {
    set_stocks();
    
    if (_attrs.length == 0) {
      $('#attrdiv')[0].style.display = 'none';
      $('#attr_title')[0].style.borderBottom = '1px solid #222';
      $('#attr_content')[0].style.borderBottom = '1px solid #222';
      return;
    }
    $('#attrdiv')[0].style.display = 'table-row';
    $('#attr_title')[0].style.borderBottom = 'none';
    $('#attr_content')[0].style.borderBottom = 'none';
    
    var con, elm, div, table, tr, td;
    con = $('#attrs')[0];
    MyUtils.removeChildElements(con);
    for (var idx in _attrs) {
      var obj = _attrs[idx];
      table = document.createElement('table');
      table.className = 'form2';
      table.cellPadding = 0;
      table.cellSpacing = 0;
      con.appendChild(table);
      tr = table.insertRow(-1);
      td = tr.insertCell(-1);
      td.className = 'header';
      td.style.width = '15px';
      td.appendChild(document.createTextNode((parseInt(idx, 10) + 1) + '.'));
      td = tr.insertCell(-1);
      td.className = 'header';
      td.style.width = '60px';
      //Create attr
      var opts = {
        obj: obj,
      };
      var chg_func = function(opts) {
        save_attr(opts.obj);
      };
      var del_func = function(opts) {
        var r = window.confirm('Delete attr will reset item table, continue?');
        if (!r) {
          return;
        }
        $.ajax({
          type: "POST",
          url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
          data: "action=del_attr&q=" + encodeURIComponent(JSON.stringify(opts.obj)),
          success: function(msg){
            var rslt = JSON.parse(msg);
            _objects = rslt._objects;
            __remove(opts.obj, _attrs);
            set_attrs(); 
          }
        });
      };
      td.appendChild(__get_imgbtn(obj.name, chg_func, del_func, opts));
      
      td = tr.insertCell(-1);
      td.className = 'header';
      td.style.textAlign = 'right';
      elm = document.createElement('button');
      elm.className = 'imgbtn add2';
      elm.appendChild(document.createTextNode('New Opt'));
      elm._obj = obj;
      elm.onclick = function() {
        save_attr_opt(null, this._obj);
      };
      td.appendChild(elm);
      tr = table.insertRow(-1);
      td = tr.insertCell(-1);
      td.colSpan = 3;
      td.className = 'content';
      for (var idx2 in obj._opts) {
        var obj2 = obj._opts[idx2];
        //Create opts
        var opts = {
          obj: obj,
          obj2: obj2
        };
        var chg_func = function(opts) {
          save_attr_opt(opts.obj2, opts.obj);
        };
        var del_func = function(opts) {
          if (opts.obj._opts.length <= 1) {
            window.alert('Can\'t delete last opt');
            return;
          }
          var r = window.confirm('Are You Sure?');
          if (r) {
            opts.obj2._objects = __get_chgd(_objects);
            $.ajax({
              type: "POST",
              url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
              data: "action=del_attr_opt&q=" + encodeURIComponent(JSON.stringify(opts.obj2)),
              success: function(msg){
                var rslt = JSON.parse(msg);
                _objects = rslt._objects;
                __remove(opts.obj2, opts.obj._opts);
                set_attrs(); 
              }
            });
          }
        };
        elm = __get_imgbtn(obj2.name, chg_func, del_func, opts);
        elm.className += ' form3dark';
        td.appendChild(elm);
      }
    }

    table = document.createElement('table');
    table.className = 'list';
    table.cellSpacing = 0;
    table.cellPadding  = 0;
    con.appendChild(table);
    tr = table.insertRow(-1);
    tr.className = 'sort';
    td = tr.insertCell(-1);
    td.appendChild(document.createTextNode('Item'));
    if ($('#stock_checkbox')[0].checked) {
      td = tr.insertCell(-1);
      td.style.width = '100px';
      td.appendChild(document.createTextNode('Current Stock'));
      td = tr.insertCell(-1);
      td.style.width = '100px';
      td.appendChild(document.createTextNode('Alert if less than'));
    }
    td = tr.insertCell(-1);
    td.style.width = '80px';
    td.appendChild(document.createTextNode('+/- Price'));
    td = tr.insertCell(-1);
    td.style.width = '80px';
    td.appendChild(document.createTextNode('Mkt Price'));
    for (var idx in _objects) {
      var obj = _objects[idx];
      tr = table.insertRow(-1);
      tr.className = (idx % 2 == 0) ? 'roweven' : 'rowodd';
      td = tr.insertCell(-1);
      td.appendChild(document.createTextNode(obj.attr_opt_code));
      if ($('#stock_checkbox')[0].checked) {
        td = tr.insertCell(-1);
        elm = document.createElement('input');
        elm.type = 'text';
        elm.value = obj.stock;
        if (parseFloat(obj.stock, 10) <= parseFloat(obj.stock_alert, 10) && obj.stock_alert != 0) {
          elm.style.color = '#ff0000';
        }
        elm._obj = obj;
        elm.onchange = function() {
          this._obj.stock = this.value;
          this._obj._c = 1;
        }
        td.appendChild(elm);
        td = tr.insertCell(-1);
        elm = document.createElement('input');
        elm.type = 'text';
        elm.value = obj.stock_alert;
        elm._obj = obj;
        elm.onchange = function() {
          this._obj.stock_alert = this.value;
          this._obj._c = 1;
        }
        td.appendChild(elm);
      }
      td = tr.insertCell(-1);
      elm = document.createElement('input');
      elm.type = 'text';
      elm.value = obj.diff_price;
      elm._obj = obj;
      elm.onchange = function() {
        this._obj.diff_price = this.value;
        this._obj._c = 1;
        set_attrs();
      }
      td.appendChild(elm);
      td = tr.insertCell(-1);
      td.id = 'realprice' + obj.id;
      td.appendChild(document.createTextNode((parseFloat($('#price')[0].value, 10) + parseFloat(obj.diff_price, 10)).toFixed(2)));
      if ($('#member_checkbox')[0].checked) {
        elm = document.createElement('span');
        elm.style.marginLeft = '5px';
        elm.appendChild(document.createTextNode('(m)'));
        td.appendChild(elm);
        td.title = '';
        for (var idx2 in _members) {
          var obj2 = _members[idx2];
          var is_exist = false;
          for (idx3 in _member_prices) {
            var obj3 = _member_prices[idx3];
            if (obj3.member_id == obj2.id) {
              td.title += __get_lt('Member (' + obj2.title + ')', 20) + '\t' + (parseFloat(obj3.price, 10) + parseFloat(obj.diff_price, 10)).toFixed(2) + '\n';
              is_exist = true;
            }
          }
          if (!is_exist) {
            td.title += __get_lt('Member (' + obj2.title + ')', 20) + '\t' + (parseFloat($('#price')[0].value, 10) + parseFloat(obj.diff_price, 10)).toFixed(2) + '\n';
          }
          td.appendChild(elm);
        }
      }
    }
    parent.updateHeight_<?php echo $instance_id; ?>();
  }

  function set_members() {
    set_attrs();
    
    if (!$('#member_checkbox')[0].checked) {
      $('#memberdiv')[0].style.display = 'none';
      $('#member_title')[0].style.borderBottom = '1px solid #222';
      $('#member_content')[0].style.borderBottom = '1px solid #222';
      return;
    }
    $('#memberdiv')[0].style.display = 'table-row';
    $('#member_title')[0].style.borderBottom = 'none';
    $('#member_content')[0].style.borderBottom = 'none';
    
    var con, elm, table, tr, td;
    con = $('#members')[0];
    MyUtils.removeChildElements(con);

    table = document.createElement('table');
    table.cellPadding = 0;
    table.cellSpacing = 0;
    table.className = 'list';
    con.appendChild(table);
    tr = table.insertRow(-1);
    tr.className = 'sort';
    td = tr.insertCell(-1);
    td.style.background = "#aaa";
    td.colSpan = 2;
    td.appendChild(document.createTextNode('Member Price'));
    for (var idx in _members) {
      var obj = _members[idx];
      tr = table.insertRow(-1);
      td = tr.insertCell(-1);
      td.className = 'title light';
      td.appendChild(document.createTextNode(obj.title));
      td = tr.insertCell(-1);
      td.className = 'content';
      elm = document.createElement('input');
      elm.type = 'text';
      elm.value = $('#price')[0].value;
      elm._member_id = obj.id;
      elm.name = 'member_price_mark';
      for (idx2 in _member_prices) {
        var obj2 = _member_prices[idx2];
        if (obj2.member_id == obj.id) {
          elm.value = obj2.price;
          elm._id = obj2.id;
        }
      }
      td.appendChild(elm);
    }
    parent.updateHeight_<?php echo $instance_id; ?>();
  }
  
  function save() {
    var elms = document.getElementsByName('member_price_mark');
    var mp = [];
    for (var idx2 in elms) {
      var obj2 = elms[idx2];
      if (!obj2._member_id) {
        continue;
      }
      var tmp = {
        product_track_id: '<?php echo $product_track_id; ?>',
        member_id: obj2._member_id,
        price: obj2.value
      };
      if (obj2._id) {
        tmp.id = obj2._id;
      }
      mp[mp.length] = tmp;
    }
    var obj = {
      <?php if ($item) echo "id: $item->id,"; ?>
      track_id: '<?php echo $product_track_id; ?>',
      enabled_stock: ($('#stock_checkbox')[0].checked) ? 1 : 0,
      enabled_delivery: ($('#ship_checkbox')[0].checked) ? 1 : 0,
      enabled_member_price: ($('#member_checkbox')[0].checked) ? 1 : 0,
      brand_id: $('#brand_select')[0].options[$('#brand_select')[0].selectedIndex].value,
      category_id: $('#category_select')[0].options[$('#category_select')[0].selectedIndex].value,
      name: $('#name')[0].value,
      price: $('#price')[0].value,
      stock: $('#stock')[0].value,
      stock_alert: $('#stock_alert')[0].value,
      intro: $('#intro')[0].value,
      details: tinyMCE.get('detail').getContent(),
      status: ($('#available')[0].checked) ? 1 : 0,
      sold__: 0,
      alert__: 0,
      _objects: __get_chgd(_objects),
      _member_prices: mp
    };
    $.ajax({
      type: "POST",
      url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
      data: "action=save&q=" + encodeURIComponent(JSON.stringify(obj)),
      success: function(msg){
//        parent.location.href = 'http://<?php echo URL . "admin.php?i=$page_id"; ?>';
        parent.location.reload();
      }
    });
  }

  function set_brand() {
    var b_sel = $('#brand_select')[0];
    b_sel.options[b_sel.options.length] = new Option('-', 0);
    for (var i in _brands) {
      var brand = _brands[i];
      var opt = new Option(brand.name, brand.id);
      b_sel.options[b_sel.options.length] = opt;
      if (_item && _item.brand_id == brand.id) {
        b_sel.selectedIndex = b_sel.options.length - 1;
      }
    }
  };

  function set_category(node, elm, prefix) {
    node.title = (node.name) ? node.name : node.title;
    if (node.title == 'Root') {
      node.title = '-';
    }
    var opt = new Option(((prefix == '') ? '' : prefix + ') ' ) + ((node.id != 0 && (node.title == '' || !node.title)) ? 'Untitled' : node.title), node.id);
    elm.options[elm.options.length] = opt;
    if (_item && _item.category_id == node.id) {
      elm.selectedIndex = elm.options.length - 1;
    }
    for (var idx in node._children) {
      var obj = node._children[idx];
      set_category(obj, elm, ((prefix == '') ? '(' : '\u2002' + prefix + '-' ) + (parseInt(idx, 10) + 1));
    }
  }

  function save_attr(obj) {
    if (!obj && _attrs.length > 0) {
      var r = window.confirm('Add attr will reset item table, continue?');
      if (!r) {
        return;
      }
    }
    var r = window.prompt('Attribute Name (e.g. Color)', (obj) ? obj.name : '');
    if (r != null) {
      if (!obj) {
        var obj = {
          product_track_id: '<?php echo $product_track_id; ?>',
          name: r,
          _opts: []
        };
      }
      obj.name = r;
      $.ajax({
        type: "POST",
        url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
        data: "action=save_attr&q=" + encodeURIComponent(JSON.stringify(obj)),
        success: function(msg){
          var rslt = JSON.parse(msg);
          if (!obj.id) {
            _attrs.push(rslt);
          }
          _objects = rslt._objects;
          __sort(_attrs);
          set_attrs();
        }
      });
    }
  }

  function save_attr_opt(obj, attr) {
    var r = window.prompt('Option Name (e.g. Balck, White)', (obj) ? obj.name : '');
    if (r != null) {
      if (!obj) {
        var obj = {
          product_track_id: '<?php echo $product_track_id; ?>',
          product_attr_id: attr.id,
          name: r,
          file: ''
        };
      }
      obj.name = r;
      obj._objects = __get_chgd(_objects);
      $.ajax({
        type: "POST",
        url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
        data: "action=save_attr_opt&q=" + encodeURIComponent(JSON.stringify(obj)),
        success: function(msg){
          var rslt = JSON.parse(msg);
          if (!obj.id) {
            attr._opts.push(rslt);
          }
          _objects = rslt._objects;
          __sort(attr._opts);
          set_attrs();
        }
      });
    }
  }

  function __get_img(img_obj) {
    var table, tr, td, elm, a, img;
    table = document.createElement('table');
    table.className = 'form4';
    table.cellPadding = 0;
    table.cellSpacing = 0;
    tr = table.insertRow(-1);
    td = tr.insertCell(-1);
    td.style.textAlign = 'right';
    td.className = 'img';
    elm = document.createElement('img');
    elm.src = 'assets/imgs/def.png';
    if (img_obj.is_default == 0) {
      elm.src = 'assets/imgs/def2.png';
      elm.onclick = function() {
        img_obj.is_default = 1;
        $.ajax({
          type: "POST",
          url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
          data: "action=set_def&q=" + encodeURIComponent(JSON.stringify(img_obj)),
          success: function(msg){
            for (var idx in _images) {
              var obj = _images[idx];
              obj.is_default = 0;
            }
            img_obj.is_default = 1;
            set_images();
          }
        });
      };
    }
    td.appendChild(elm);
    td.className = 'img';
    elm = document.createElement('img');
    elm.src = 'assets/imgs/del.png';
    elm.onclick = function() {
      var r = window.confirm('Are You Sure?');
      if (r) {
        $.ajax({
          type: "POST",
          url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
          data: "action=del_img&q=" + encodeURIComponent(JSON.stringify(img_obj)),
          success: function(msg){
            _images = JSON.parse(msg);
            set_images();
          }
        });
      }
    };
    td.appendChild(elm);
    tr = table.insertRow(-1);
    td = tr.insertCell(-1);
    a = document.createElement('a');
    a.rel = 'prettyPhoto[gallery1]';
    a.href = img_obj.file;
    td.appendChild(a);
    img = document.createElement('img');
    img.src = img_obj.file;
    img.style.width = '60px';
    a.appendChild(img);
    return table;
  }

  function __set_pp() {
    $("a[rel^='prettyPhoto']").prettyPhoto({
      social_tools: ''
    });
  }

  function __get_imgbtn(name, chg_func, del_func, opts) {
    var table, tr, td, elm;
    table = document.createElement('table');
    table.className = 'form3';
    table.cellPadding = 0;
    table.cellSpacing = 0;
    tr = table.insertRow(-1);
    td = tr.insertCell(-1);
    td.onclick = function() {
      chg_func(opts);
    };
    td.className = 'text';
    td.title = name;
    td.appendChild(document.createTextNode(name));
    td = tr.insertCell(-1);
    td.className = 'img';
    td.onclick = function() {
      chg_func(opts);
    };
    elm = document.createElement('img');
    elm.src = 'assets/imgs/edit16.png';
    td.appendChild(elm);
    td = tr.insertCell(-1);
    td.className = 'img';
    td.onclick = td.onclick = function() {
      del_func(opts);
    };
    elm = document.createElement('img');
    elm.src = 'assets/imgs/delete24.png';
    td.appendChild(elm);
    return table;
  }

  function __remove(item, array) {
    for (var idx in array) {
      var obj = array[idx];
      if (obj.id == item.id) {
        array.splice(idx, 1);
      }
    }
  }

  function __sort(arr) {
    var func = function(a, b) {
      return parseInt(a.id, 10) > parseInt(b.id, 10);
    };
    arr.sort(func);
  }

  function __get_chgd(arr) {
    var rslt = [];
    for (var idx in arr) {
      var obj = arr[idx];
      if (obj._c == 1) {
        rslt[rslt.length] = obj;
      }
    }
    return rslt;
  }

  function __get_lt(title, length) {
    for (var i = 0, il =  length - title.length; i < il; i++) {
      title += '\xa0';
    }
    return title;
  }
</script>
</body>
</html>